package com.fs.controller.user;

import com.fs.constant.JwtClaimsConstant;
import com.fs.dto.CartAddDTO;
import com.fs.properties.JwtProperties;
import com.fs.result.Result;
import com.fs.service.CartService;
import com.fs.utils.JwtUtil;
import com.fs.vo.CartVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user/cart")
@Api(tags = "用户端-购物车接口")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/add")
    @ApiOperation("添加商品到购物车")
    public Result<String> addToCart(@RequestBody CartAddDTO cartAddDTO,
                                    HttpServletRequest request) {
        log.info("添加商品到购物车: {}", cartAddDTO);

        // 从 token 中解析 userId（示例逻辑）
        Long userId = TokenUserId(request);

        cartService.addToCart(userId, cartAddDTO);
        return Result.success("已加入购物车");
    }


    @GetMapping("/list")
    @ApiOperation("查询购物车列表")
    public Result<List<CartVO>> list(HttpServletRequest request) {
        Long userId = TokenUserId(request);

        List<CartVO> cartList = cartService.list(userId);
        return Result.success(cartList);
    }


    //获取token中的userid
    private Long TokenUserId(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            token = request.getHeader("token"); // 兼容 Swagger
        }

        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        // 解密 token
        String secretKey = jwtProperties.getAdminSecretKey();
        Claims claims = JwtUtil.parseJWT(secretKey, token);
        // ⚠️ 注意这里改成 userId（与生成端一致）
        Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);
        Long userId = Long.valueOf(userIdObj.toString());
        return userId;
    }

}
